<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="800px"
    title="新建营销政策"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :inline="true"
      :rules="formRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="产品名称"
            prop="productId"
            style="width: 100%"
          >
            <el-select
              v-model="formData.productId"
              style="width: 100%;"
              filterable
              clearable
              remote
              reserve-keyword
              :remote-method="proRemoteMethod"
              :loading="proLoading"
              value-key="id"
              placeholder="请搜索并选择产品"
              @change="selectChange"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.productPopularName"
                :value="item.id"
              >
                <div class="pro-item">
                  <span>{{ getProductName(item) }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          v-if="currentSelect"
          :span="12"
        >
          <el-form-item
            label="商品名"
            style="width: 100%"
          >
            <span>{{ currentSelect?.productName || '无' }}</span>
          </el-form-item>
        </el-col>
        <el-col
          v-if="currentSelect"
          :span="12"
        >
          <el-form-item
            label="包装规格"
            style="width: 100%"
          >
            <span>{{ currentSelect?.packSpecs }}</span>
          </el-form-item>
        </el-col>
        <el-col
          v-if="currentSelect"
          :span="12"
        >
          <el-form-item
            label="生产厂家"
            style="width: 100%"
          >
            <span>{{ currentSelect?.producer || '无' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            style="width: 100%"
            label="适用地区"
            prop="area"
          >
            <el-cascader
              ref="cascader"
              v-model="formData.area"
              :popper-append-to-body="false"
              style="width: 100%;"
              :options="citys.map(o => ({ ...o, 'children': null}))"
              placeholder="请选择适用地区"
              :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
              collapse-tags
              clearable
              @change="areaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="政策文件"
            style="width: 100%"
            prop="files"
          >
            <upload-file-view :file-arr="formData.files" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import area from '@/utils/area.js'

export default defineComponent({
  name: 'CreatePolicy',
  emits: ['handleSuccess'],
  setup(props, context) {
    const api = inject('api')
    const formRef = ref(null)
    const currentInstance = getCurrentInstance()
    var datas = reactive({
      citys: area,
      cascader: null,
      formData: {
        productId: '',
        region: [],
        files: [],
      },
      proLoading: false,
      productOptions: [],
      currentSelect: null,
    })
    var formRules = reactive({
      productId: [
        {
          required: true,
          message: '请选择产品，可模糊搜索',
          trigger: 'change',
        },
      ],
      area: [
        {
          required: true,
          message: '请选择适用地区',
          trigger: 'change',
        },
      ],
    })
    var formLabelWidth = ref(100)
    var dialogShow = ref(false)
    const open = (productId) => {
      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      datas.currentSelect = null
      formRef.value.resetFields()
    }
    const proRemoteMethod = async(query) => {
      if (query !== '') {
        datas.proLoading = true
        var pro = await api.common.GET_PRODUCT_LIST({ keyWord: query })
        if (pro.code === 0) {
          datas.productOptions = pro.data.list
        } else {
          datas.productOptions = []
        }
        datas.proLoading = false
      } else {
        datas.productOptions = []
      }
    }
    const selectChange = (id) => {
      var item = datas.productOptions.find((p) => p.id)
      if (item) {
        datas.currentSelect = item
      }
    }
    const areaChange = (val) => {
      console.log(val)
      datas.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        datas.cascader.getCheckedNodes()
      )
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          api.marketingPolicy
            .MARKETING_POLICY_CREATE(datas.formData)
            .then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '提交成功',
                })
                context.emit('handleSuccess')
                close()
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      formRef,
      ...toRefs(datas),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      proRemoteMethod,
      selectChange,
      areaChange,
    }
  },
})
</script>
